//
//  ST_MaidWayManager.swift
//  btvideo
//
//  Created by Jason on 2021/8/5.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import MBProgressHUD

class ST_MaidWayManager: NSObject {

    static let shared = ST_MaidWayManager()
    
    var count = 0
    
    var count_array: [Int] = [3, 3, 3, 6, 6]
    
    fileprivate override init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(check_status), name: NSNotification.Name.refreshStatusWhenBackApp, object: nil)
    }
    
    fileprivate weak var delegate: ST_TIANPaymentTransactionStateDelegate?
    
    // 付费来源
    var source: ST_MaidWaySource? {
        didSet {
            guard let s = source else { return }
            parameters.updateValue(s.rawValue.string, forKey: "source")
        }
    }
    
    fileprivate var give_user_id: String? {
        didSet {
            if let id = give_user_id {
                parameters.updateValue(id, forKey: "target_accid")
            }else {
                parameters.removeValue(forKey: "target_accid")
            }
        }
    }

    fileprivate var parameters = [String: Any]()

}

extension ST_MaidWayManager {
    
    @objc fileprivate func check_status() {
        self.check(show: true)
    }

    @objc fileprivate func check(show: Bool) {
        guard let otn = SC.need_check_o_t_n else {
            return
        }
        if show {
            self.delegate?.show_tip(str: "正在同步支付结果，请耐心等待...")
        }
        
        JVrequest(PH.BASE_URL + "vdsns/pay/isPay/v1.json" + "?otn=\(otn)") { json in
            SC.need_check_o_t_n = nil
            ST_LaunchChargeWidget.shared.fetch_boot_data()
            self.get_user_status()
        } failure: { code, errStr in
            if self.count == self.count_array.count - 1 {
                SC.need_check_o_t_n = nil
                self.count = 0
                self.delegate?.show_tip(str: "未检测到支付，若您已支付，请稍后刷新再试或联系客服。")
            }else {
                self.count += 1
                let s = self.count_array[safe: self.count] ?? 1
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(s)) {
                    self.check(show: false)
                }
            }
        }
    }
    
    fileprivate func get_user_status() {
        JVrequest(PH.BASE_URL + "vdsns/payOrderV73/getMemberRfq/v2.json") { json in
            self.delegate?.transaction_succeed()
            ST_BTUserInfoManager.shared.additional_attributes?.liveTalkFreeNumber = json["data"]["free_once"].intValue
            ST_BTUserInfoManager.shared.modify_current_account(receiptResponse: json["data"])
            NotificationCenter.default.post(name: Notification.Name.in_pur_status_success, object: nil)
        } failure: { code, errStr in
            self.delegate?.transaction_succeed()
        }
    }
    
}

extension ST_MaidWayManager {
    
    func doWay(id: String, giveId: String = "", delegate: ST_TIANPaymentTransactionStateDelegate) {
        self.delegate = delegate
        
        var aid: String?
        var to: String?
        
        if let a = ST_BTUserInfoManager.shared.current_account_info?.accid, let t = ST_BTUserInfoManager.shared.current_account_info?.token {
            aid = a
            to = t
        }
        if let a = ST_RegisterMonitor.shared.regist_response_account()?.accid, let t = ST_RegisterMonitor.shared.regist_response_account()?.token {
            aid = a
            to = t
        }
        
        guard let accid = aid, let token = to else {
            self.delegate?.show_tip(str: "发生意外错误，请重新登录后再试")
            return
        }

        let alert = ST_MaidSelectWayViewController()
        alert.overCurrentContext = true
        alert.over_current_context_alpha = "0.4"
        GlobalPresent(toController: alert)
        
        alert.choose_block = {[weak self] way in
            if way == 0 {
                JVrequest(PH.BASE_URL + "vdsns/aliPay/getOtn/v1.json") { json in
                    let o = json["data"]["otn"].stringValue
                    SC.need_check_o_t_n = o
                    let urlStr = PH.BASE_URL + "vdsns/aliPay/pay/v1.json" + "?accid=\(accid)&token=\(token)&product_id=\(id)&otn=\(o)&channel=ios_mma"
                    
                    let vc = ST_MaidWayWebViewController()
                    vc.urlStr = urlStr
                    vc.overCurrentContext = true
                    vc.over_current_context_alpha = "0.0"
                    GlobalPresent(toController: vc, animated: false)
                } failure: { code, errStr in
                    self?.delegate?.show_tip(str: "请稍后再试")
                }
            }
            
            if way == 1 {
                JVrequest(PH.BASE_URL + "vdsns/pay/getOtn/v1.json") { json in
                    let o = json["data"]["otn"].stringValue
                    SC.need_check_o_t_n = o
                    let urlStr = PH.BASE_URL + "vdsns/pay/index/v1.json" + "?accid=\(accid)&token=\(token)&product_id=\(id)&otn=\(o)&channel=ios_mma"
                    
                    let vc = ST_MaidWayWebViewController()
                    vc.urlStr = urlStr
                    vc.overCurrentContext = true
                    vc.over_current_context_alpha = "0.0"
                    GlobalPresent(toController: vc, animated: false)
                } failure: { code, errStr in
                    self?.delegate?.show_tip(str: "请稍后再试")
                }
            }
        }
    }
    
}
